package com.alks.function.service.impl.finance.salary;

import com.alibaba.fastjson2.JSON;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.config.handler.TextFooterEventHandler;
import com.alks.common.config.handler.TextHeadEventHandler;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.ITextPdfUtils;
import com.alks.common.utils.UserInfoUtil;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.common.utils.beanutils.StringUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.common.utils.stringUtils.ZStringUtils;
import com.alks.entity.data.entity.PcBasicSalaryBsChg;
import com.alks.entity.data.entity.PcBasicSalaryWtChg;
import com.alks.entity.data.entity.PcCuttingSalary;
import com.alks.entity.data.entity.PcEmployeeWorkType;
import com.alks.entity.data.entity.dispatch.MonthBonusEnd;
import com.alks.entity.data.entity.imes.CutProdDetailSalary;
import com.alks.entity.data.page.PageRecord;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.PcCuttingSalaryDto;
import com.alks.function.data.dto.administration.ChangeDto;
import com.alks.function.data.dto.administration.PcEmployeeWokeTypeDto;
import com.alks.function.data.dto.finance.salary.EmployeeListDto;
import com.alks.function.data.dto.finance.salary.PcBasicSalaryWtChgDto;
import com.alks.function.data.request.PcCuttingSalaryReq;
import com.alks.function.data.request.administration.JobTypeChangeRequest;
import com.alks.function.data.request.finance.salary.JobTypeRequest;
import com.alks.function.data.request.finance.salary.getEmployeeRequest;
import com.alks.function.data.request.finance.salary.getPcEmployeeWorkTypeRequest;
import com.alks.function.mapper.administration.PcEmployeeMapper;
import com.alks.function.mapper.finance.salary.SalaryFileCreationMapper;
import com.alks.function.service.async.PcCuttingAsyncService;
import com.alks.function.service.finance.salary.SalaryFileCreationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.font.FontProvider;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Service
@Slf4j
public class SalaryFileCreationServiceImpl implements SalaryFileCreationService {

    private static final String salary_redis = "salary-cutting-redis";
    @Autowired
    PcCuttingAsyncService service;
    @Resource
    private SalaryFileCreationMapper salaryFileCreationMapper;

    @Resource
    private PcEmployeeMapper pcEmployeeMapper;

    @Autowired
    RedisService redisService;

    /**
     * 工种工资建档-查询
     *
     * @param workType
     * @return
     */
    @Override
    public ResponseInfo ListOfWagesForJobTypes(String workType) {
        return ResponseInfo.ok(salaryFileCreationMapper.getPcEmployeeWokeTypeSalaryList(workType));
    }

    /**
     * 工种工资建档-插入
     *
     * @param map
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo JobTypeSalaryUpdate(Map<String, String> map) {
        String workType = map.get("workType");
        String salary = map.get("salary");
        if (ObjectUtils.isEmpty(workType)) {
            return ResponseInfo.error("工种不能为空!");
        }
        if (ObjectUtils.isEmpty(salary)) {
            return ResponseInfo.error("工资不能为空!");
        }
        String employeeWorkType = pcEmployeeMapper.getWorkTypToPcEmployeeWorkType(workType);
        if (ObjectUtils.isEmpty(employeeWorkType)) {
            return ResponseInfo.error("该工种不在工种建档中存在!");
        }
        Integer employeeCalcType = salaryFileCreationMapper.getEmployeeCalcType(workType);
        Integer employeeTempCalcType = salaryFileCreationMapper.getEmployeeTempCalcType(workType);
        if (employeeCalcType <= 0 && employeeTempCalcType <= 0) {
            return ResponseInfo.error("该工种在人事计时中不存在!");
        }
        BigDecimal pcEmployeeWorkTypeToSalary = pcEmployeeMapper.getPcEmployeeWorkTypeToSalary(workType);
        if (salary.equals(String.valueOf(pcEmployeeWorkTypeToSalary))) {
            return ResponseInfo.error("变更前工种基础薪资与变更后相同!");
        }
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        if (pcEmployeeWorkTypeToSalary != null && pcEmployeeWorkTypeToSalary.compareTo(BigDecimal.ZERO) > 0) {
            PcBasicSalaryWtChg pcBasicSalaryWtChg = new PcBasicSalaryWtChg();
            pcBasicSalaryWtChg.setCompanyId(userInfo.getCompanyId());
            pcBasicSalaryWtChg.setSysDate(LocalDateTime.now());
            pcBasicSalaryWtChg.setSysUser(userInfo.getUserName());
            pcBasicSalaryWtChg.setWorkType(workType);
            pcBasicSalaryWtChg.setSalaryAlw(pcEmployeeWorkTypeToSalary);
            pcBasicSalaryWtChg.setNewSalaryAlw(BigDecimal.valueOf(Long.parseLong(salary)));
            salaryFileCreationMapper.addPcBasicSalaryWtChg(pcBasicSalaryWtChg);
        }
        salaryFileCreationMapper.UpdatePcEmployeeWokeTypeSalary(workType, salary, userInfo.getUserName(), LocalDateTime.now());
        //同步更新员工资料计时工种薪资
        List<String> list = salaryFileCreationMapper.getUpdateByWorkType(workType);
        if (!ObjectUtils.isEmpty(list)) {
            salaryFileCreationMapper.updatePcBasicSalary(new BigDecimal(salary), LocalDateTime.now(), list);
        }
        return ResponseInfo.ok();
    }

    /**
     * 工种变更查询
     *
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo JobTypeChangeInquiry(JobTypeRequest request) {
        PageRecord<PcBasicSalaryWtChgDto> list = new PageRecord<>();
        List<PcBasicSalaryWtChgDto> pcBasicSalaryWtChgList = salaryFileCreationMapper.getPcBasicSalaryWtChgList(request);
        PageInfo pageInfo = new PageInfo(pcBasicSalaryWtChgList);
        list.setList(pcBasicSalaryWtChgList);
        list.setTotal(pageInfo.getTotal());
        return ResponseInfo.ok(list);
    }

    /**
     * 员工资料明细
     *
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo EmployeeList(getEmployeeRequest request) {
        PageRecord<EmployeeListDto> list = new PageRecord<>();
        List<EmployeeListDto> employeeList = salaryFileCreationMapper.getEmployeeList(request);
        for (EmployeeListDto dto : employeeList) {
            dto.setStatus(dto.getStatus().equals("1") ? "在职" : "离职");
        }
        PageInfo pageInfo = new PageInfo(employeeList);
        list.setList(employeeList);
        list.setTotal(pageInfo.getTotal());
        return ResponseInfo.ok(list);
    }

    /**
     * 员工资料变更明细
     *
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo ChangeQuery(getEmployeeRequest request) {
        PageRecord<ChangeDto> list = new PageRecord<>();
        List<ChangeDto> employeeList = salaryFileCreationMapper.getEmployeeChangeQuery(request);
        PageInfo pageInfo = new PageInfo(employeeList);
        list.setList(employeeList);
        list.setTotal(pageInfo.getTotal());
        return ResponseInfo.ok(list);
    }

    /**
     * 变更确认
     *
     * @param request
     * @return
     */
    @Override
    public ResponseInfo ChangeConfirmation(JobTypeChangeRequest request) {
        if (ObjectUtils.isEmpty(request.getWorkerIdList())) {
            return ResponseInfo.error("请选择记录!");
        }
        if (ObjectUtils.isEmpty(request.getWorkTypeSalary())) {
            return ResponseInfo.error("请输入基本工资!");
        }
        List<PcBasicSalaryBsChg> list = new ArrayList<>();
        for (String t : request.getWorkerIdList()) {
            UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
            EmployeeListDto employeeList2 = salaryFileCreationMapper.getEmployeeList2(t);
            PcBasicSalaryBsChg pcBasicSalaryBsChg = new PcBasicSalaryBsChg();
            BeanUtil.copyProperties(employeeList2, pcBasicSalaryBsChg);
            pcBasicSalaryBsChg.setNewBasicSalary(request.getWorkTypeSalary());
            pcBasicSalaryBsChg.setSysUser(userInfo.getUserName());
            pcBasicSalaryBsChg.setSysDate(LocalDateTime.now());
            pcBasicSalaryBsChg.setCompanyId(userInfo.getCompanyId());
            list.add(pcBasicSalaryBsChg);
        }
        if (!ObjectUtils.isEmpty(list)) {
            salaryFileCreationMapper.addPcBasicSalaryBsChgList(list);
            salaryFileCreationMapper.updatePcBasicSalary(request.getWorkTypeSalary(), LocalDateTime.now(), request.getWorkerIdList());
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 工种工资建档-查询
     *
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo JobTypeFilingQuery(getPcEmployeeWorkTypeRequest request) {
        PageRecord<PcEmployeeWokeTypeDto> list = new PageRecord<>();
        List<PcEmployeeWokeTypeDto> wokeTypeList = salaryFileCreationMapper.getJobTypeFilingQuery(request);
        PageInfo pageInfo = new PageInfo(wokeTypeList);
        list.setList(wokeTypeList);
        list.setTotal(pageInfo.getTotal());
        return ResponseInfo.ok(list);
    }

    /**
     * 工种工资建档-新增
     *
     * @param request
     * @return
     */
    @Override
    public ResponseInfo JobTypeFilingAdd(getPcEmployeeWorkTypeRequest request) {
        if (ObjectUtils.isEmpty(request.getWorkType())) {
            return ResponseInfo.error("请输入工种!");
        }
        if (ObjectUtils.isEmpty(request.getWorkTypeShort())) {
            return ResponseInfo.error("请输入简称!");
        }
        String workTypToPcEmployeeWorkType = pcEmployeeMapper.getWorkTypToPcEmployeeWorkType(request.getWorkType());
        if (!ObjectUtils.isEmpty(workTypToPcEmployeeWorkType)) {
            return ResponseInfo.error("该工种已存在,不可重复添加!");
        }
        PcEmployeeWorkType pcEmployeeWorkType = new PcEmployeeWorkType();
        String userName = UserIdThread.get().getUserName();
        String companyId = UserIdThread.get().getCompanyId();
        pcEmployeeWorkType.setCompanyId(companyId);
        pcEmployeeWorkType.setSysUser(userName);
        pcEmployeeWorkType.setSysDate(LocalDateTime.now());
        pcEmployeeWorkType.setWorkType(request.getWorkType());
        pcEmployeeWorkType.setCalcType(request.getCalcType());
        pcEmployeeWorkType.setWorkTypeShort(request.getWorkTypeShort());
        pcEmployeeMapper.addPcEmployeeWorkType(pcEmployeeWorkType);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 工种工资建档-删除
     *
     * @param workTypeSeq
     * @return
     */
    @Override
    public ResponseInfo JobTypeFilingDel(String workTypeSeq) {
        if (ObjectUtils.isEmpty(workTypeSeq)) {
            return ResponseInfo.error("序号为空不能删除!");
        }
        String workType = pcEmployeeMapper.getPcEmployeeWorkType(workTypeSeq);
        Integer workTypToPcEmployee = pcEmployeeMapper.getWorkTypToPcEmployee(workType);
        if (workTypToPcEmployee != null && workTypToPcEmployee > 0) {
            return ResponseInfo.error("员工已有此工种,不可删除!");
        }
        Integer workTypToPcEmployeeTemp = pcEmployeeMapper.getWorkTypToPcEmployeeTemp(workType);
        if (workTypToPcEmployeeTemp != null && workTypToPcEmployeeTemp > 0) {
            return ResponseInfo.error("员工已有此工种,不可删除!");
        }
        pcEmployeeMapper.delPcEmployeeWorkType(workTypeSeq);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 工种工资建档-修改
     *
     * @param request
     * @return
     */
    @Override
    public ResponseInfo JobTypeFilingUpdate(getPcEmployeeWorkTypeRequest request) {
        if (ObjectUtils.isEmpty(request.getWorkTypeSeq())) {
            return ResponseInfo.error("序号为空不能修改!");
        }
        if (ObjectUtils.isEmpty(request.getWorkTypeShort())) {
            return ResponseInfo.error("请输入简称!");
        }
        String userName = UserIdThread.get().getUserName();
        salaryFileCreationMapper.updatePcEmployeeWorkTypeShort(request.getWorkTypeSeq(), request.getWorkTypeShort(), request.getCalcType(), userName, LocalDateTime.now());
        return ResponseInfo.ok("操作成功!");
    }

    @Override
    public ResponseInfo getPcCuttingSalary(PcCuttingSalaryReq req) {
        String lotNo = req.getLotNo();
        service.downPcCuttingSalary(req);
        Map<String, Object> map = new HashMap<>();
        String lot = salaryFileCreationMapper.getLot(lotNo);
        if (lotNo != null && !lotNo.isEmpty()) {
            if (lot == null || lot.isEmpty()) {
                List<String> lotNos = salaryFileCreationMapper.getLotByPcLotHead(lotNo);
                if (lotNos != null && !lotNos.isEmpty()) return ResponseInfo.ok(lotNos);
                return ResponseInfo.error("请输入正确的指令号");
            }
        }
        if (req.getPageNum() == null || req.getPageSize() == null) {
            req.setPageNum(1);
            req.setPageSize(10);
        }
        Set scan = redisService.scan(salary_redis);
        if (!ZStringUtils.noeNotNull(req) && req.getPageNum() == 1 && req.getPageSize() == 40) {
            if (scan.size() > 0) {
                String string = redisService.get(salary_redis);
                List<PcCuttingSalary> list = JSON.parseArray(string, PcCuttingSalary.class);
                map.put("list", list);
                return ResponseInfo.ok(map);
            }
        }
        PageHelper.startPage(req.getPageNum(), req.getPageSize(), false);
        List<PcCuttingSalary> list = salaryFileCreationMapper.getPcCuttingSalary(req);
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    @Override
    @Transactional
    public ResponseInfo confirmSalary(PcCuttingSalaryDto req) {
        req.setCompanyId(UserIdThread.get().getCompanyId());
        List<PcCuttingSalary> list = salaryFileCreationMapper.getPcCuttingSalary1(req);
        if (ZStringUtils.isEmpty(list)) {
            return ResponseInfo.error("未选择任何记录");
        }
        String companyId = UserIdThread.get().getCompanyId();
        switch (req.getChoose()) {
            case "1":
                if (req.getFinanceYymm().length() != 6) {
                    return ResponseInfo.error("结算月份有错，请核实");
                }
                Set<String> set = new HashSet<>();
                List<PcCuttingSalary> newList = new ArrayList<>();
                MonthBonusEnd monthBounusEnd = new MonthBonusEnd();
                monthBounusEnd.setBonusYm(req.getFinanceYymm());
                monthBounusEnd.setCompanyId(companyId);
                monthBounusEnd.setBonusType("CUT");
                monthBounusEnd = salaryFileCreationMapper.selectByPrimaryKey(monthBounusEnd);
                if (ZStringUtils.isNotNull(monthBounusEnd)) {
                    throw new ServiceErrorException(ZStringUtils.format("账期【{}】已封账，无法结算确认", new Object[]{req.getFinanceYymm()}));
                } else {
                    Iterator var7 = list.iterator();
                    while (var7.hasNext()) {
                        PcCuttingSalary cpds = (PcCuttingSalary) var7.next();
//                        if ("Y".equals(cpds.getCfmFlag())) {
//                            throw new ServiceErrorException("勾选记录存在已审核的资料!");
//                        }
                        if (!"Y".equals(cpds.getPriceFlag())) {
                            set.add(cpds.getLotNo());
                            continue;
//                            throw new ServiceErrorException("勾选记录存在单价未审核!");
                        }
                        if (ZStringUtils.isNull(cpds.getPrice())) {
                            set.add(cpds.getLotNo());
                            continue;
//                            throw new ServiceErrorException("勾选记录存在单价为0的资料!");
                        }
                        if (salaryFileCreationMapper.countByCutJz(cpds) <= 0) {
                            cpds.setCfmFlag("Y");
                            cpds.setAccountName(req.getAccountName());
                            cpds.setFinanceYymm(req.getFinanceYymm());
                            cpds.setCfmUser(UserIdThread.get().getUserName());
                            newList.add(cpds);
                        }
                    }
                    if (newList != null && newList.size() != 0) {
                        salaryFileCreationMapper.insertBatch(newList);
                        if (set != null && set.size() != 0) {
                            return ResponseInfo.error("勾选记录存在单价未审核，单价为0的指令" + set.toString());
                        }
                        return ResponseInfo.ok();
                    } else {
                        if (set != null && set.size() != 0) {
                            return ResponseInfo.error("勾选记录存在单价未审核，单价为0的指令" + set.toString());
                        }
                        return ResponseInfo.error("没有可结算的数据");
                    }
                }
            case "2":
                for (PcCuttingSalary salary : list) {
                    if (!"Y".equals(salary.getCfmFlag())) {
                        return ResponseInfo.error("勾选记录存在未结算的资料");
                    }
                    if ("Y".equals(salary.getPriceCfmFlag())) {
                        return ResponseInfo.error("存在已封账的记录，无法取消结算!");
                    }
                }
                salaryFileCreationMapper.cancelSalary(list, UserIdThread.get().getLoginName());
                return ResponseInfo.ok();
            case "3":
                List<PcCuttingSalary> list1 = req.getList();
                for (PcCuttingSalary salary : list1) {
                    if (ZStringUtils.isBlank(salary.getFinanceYymm()))
                        throw new ServiceErrorException("勾选记录存在未结算的资料");
                }
                salaryFileCreationMapper.setRemarkSalary(req, UserIdThread.get().getLoginName());
                return ResponseInfo.ok();
        }

        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo returnCondition() {
        Map<String, Object> map = new HashMap<>();
        List<String> types = salaryFileCreationMapper.getSalaryTypes();
        types.add("正单");
        types.add("补单");
        types.add("冲裁");
        types.add("手工");
        List<String> deptNames = salaryFileCreationMapper.getDeptNames();
        List<Map<String, String>> workerNames = salaryFileCreationMapper.getWorkerNames();
        List<String> partNames = salaryFileCreationMapper.getPartNames();
        map.put("types", types);
        map.put("deptNames", deptNames);
        map.put("workerNames", workerNames);
        map.put("partNames", partNames);
        return ResponseInfo.ok(map);
    }


    @Override
    public ResponseInfo getPcCuttingTotalWP(PcCuttingSalaryReq req) throws ExecutionException, InterruptedException {
        Map<String, Object> map = new HashMap<>();
        BigDecimal qtyTotal = salaryFileCreationMapper.getPcCuttingSalaryQtyTotal(req);
        BigDecimal amtTotal = salaryFileCreationMapper.getPcCuttingSalaryAmtTotal(req);
        Integer total = salaryFileCreationMapper.getPcCuttingTotal(req);
        map.put("total", total);
        map.put("qtyTotal", qtyTotal);
        map.put("amtTotal", amtTotal);
        return ResponseInfo.ok(map);
    }

    @Override
    public void downloadCuttingCollect(HttpServletResponse response, String financeYymm) throws IOException {
        if (StringUtils.isEmpty(financeYymm)) throw new ServiceErrorException("请选择月份");
        List<String> list = salaryFileCreationMapper.getLotNoByFinanceYymm(financeYymm);
        String flag = salaryFileCreationMapper.getFromBonus(financeYymm);
        if (!Objects.isNull(flag)) throw new ServiceErrorException("该月份已封账");
        List<Map<String, Object>> listMap = salaryFileCreationMapper.getPcCuttingCollect(list);
        Map<String, String> map = new HashMap<>();
        map.put("financeYymm", financeYymm);
        ExcelUtils.creatByTemplate(response, "冲裁计件汇总模板.xls", "冲裁计件汇总" + DateUtils.dateTimeNow(), listMap, map);
    }

    @Override
    public void exportPdf(HttpServletResponse response, PcCuttingSalaryReq req) {
        Map<String, Map<String, Map<String, List<CutProdDetailSalary>>>> result = getStringMapMap(req);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (result.isEmpty()) throw new ServiceErrorException("没有可导出的数据");
        DecimalFormat decimalFormat = new DecimalFormat("0.000");
        DecimalFormat amtDecimal = new DecimalFormat("0.00");
        try {
            PdfDocument pdf = new PdfDocument(new PdfWriter(response.getOutputStream()));
            PageSize rotate = PageSize.A4.rotate();
            float v = rotate.getWidth() + 25;
            float h = rotate.getHeight() + 140;
            PageSize customPageSize = new PageSize(v, h);
            Document document = new Document(pdf, customPageSize);
            PdfFontFactory.registerSystemDirectories();
            PdfFont chinese = PdfFontFactory.createRegisteredFont("microsoft yahei", "Identity-H");
            document.setFont(chinese);

            FontProvider fontProvider = new FontProvider();
            //添加自定义字体，例如微软雅黑
            fontProvider.addFont("static/fonts/yahei.ttf", PdfEncodings.IDENTITY_H);
            PdfFont pdfFont = fontProvider.getFontSet()
                    .getFonts()
                    .stream()
                    .findFirst()
                    .map(fontProvider::getPdfFont)
                    .orElse(null);
            document.getPdfDocument().addEventHandler(PdfDocumentEvent.END_PAGE, new TextFooterEventHandler(pdfFont));
            IEventHandler eventHandler = null;
            boolean isFirst = true;
            for (String workId : result.keySet()) {
                Map<String, Map<String, List<CutProdDetailSalary>>> dateMaps = result.get(workId);
                String firstDateInfo = dateMaps.keySet().iterator().next();
                Map<String, List<CutProdDetailSalary>> firstlotNoMaps = dateMaps.get(firstDateInfo);
                String firstLotNo = firstlotNoMaps.keySet().iterator().next();
                CutProdDetailSalary cpdsInfo = ((List<CutProdDetailSalary>) firstlotNoMaps.get(firstLotNo)).get(0);
                String content = "姓名： " + cpdsInfo.getWorkerName() + "              部门： " + cpdsInfo.getDeptName()+"                    打印日期： "+sdf.format(new Date());
                eventHandler = new TextHeadEventHandler(pdfFont, content);
                document.getPdfDocument().addEventHandler(PdfDocumentEvent.START_PAGE, eventHandler);
                if (!isFirst) {
                    document.add(new AreaBreak(customPageSize));
                } else {
                    isFirst = false;
                }
                Table table = new Table(12);
                table.setWidth(UnitValue.createPercentValue(102.0F));
                table.addHeaderCell(ITextPdfUtils.singleCenterCell("类型"))
                        .addHeaderCell(ITextPdfUtils.singleCenterCell("生产日期"))
                        .addHeaderCell(ITextPdfUtils.singleCenterCell("指令号"))
                        .addHeaderCell(ITextPdfUtils.singleCenterCell("型体"))
                        .addHeaderCell(ITextPdfUtils.singleCenterCell("部位"))
                        .addHeaderCell(ITextPdfUtils.singleCenterCell("裁层"))
                        .addHeaderCell(ITextPdfUtils.singleCenterCell("每双片数"))
                        .addHeaderCell(ITextPdfUtils.singleCenterCell("订单数"))
                        .addHeaderCell(ITextPdfUtils.singleCenterCell("派工数量"))
                        .addHeaderCell(ITextPdfUtils.singleCenterCell("单价"))
                        .addHeaderCell(ITextPdfUtils.singleCenterCell("金额"))
                        .addHeaderCell(ITextPdfUtils.singleCenterCell("结算月份"));
                float total = 0.0F;
                float totalQty = 0.0F;
                for (String dateKey : dateMaps.keySet()) {
                    Map<String, List<CutProdDetailSalary>> lotNoMaps = dateMaps.get(dateKey);
                    for (String lotNoKey : lotNoMaps.keySet()) {
                        List<CutProdDetailSalary> list = lotNoMaps.get(lotNoKey);
                        for (CutProdDetailSalary cpds : list) {
                            table.addCell(ITextPdfUtils.singleRightCell(cpds.getType()));
                            table.addCell(ITextPdfUtils.singleRightCell(sdf.format(cpds.getDispatchDate())));
                            table.addCell(ITextPdfUtils.singleRightCell(cpds.getLotNo()));
                            table.addCell(ITextPdfUtils.singleRightCell(cpds.getStyle()));
                            table.addCell(ITextPdfUtils.singleRightCell(cpds.getPartName()));
                            String cutLayerStr = ZStringUtils.isNull(cpds.getCutLayer()) ? "" : cpds.getCutLayer().toString();
                            table.addCell(ITextPdfUtils.singleRightCell(cutLayerStr));
                            String cutNumStr = ZStringUtils.isNull(cpds.getCutNum()) ? "" : cpds.getCutNum().toString();
                            table.addCell(ITextPdfUtils.singleRightCell(cutNumStr));
                            table.addCell(ITextPdfUtils.singleRightCell(cpds.getOrderQty().toString()));
                            String qtyStr = ZStringUtils.isNull(cpds.getDispatchQty()) ? "" : cpds.getDispatchQty().toString();
                            table.addCell(ITextPdfUtils.singleRightCell(qtyStr));
                            String priceStr = ZStringUtils.isNull(cpds.getPrice()) ? "" : decimalFormat.format(cpds.getPrice());
                            table.addCell(ITextPdfUtils.singleRightCell(priceStr));

                            total += ZStringUtils.isNull(cpds.getAmt()) ? 0.0F : cpds.getAmt().floatValue();
                            totalQty += ZStringUtils.isNull(cpds.getDispatchQty()) ? 0 : cpds.getDispatchQty();
                            String amtStr = ZStringUtils.isNull(cpds.getAmt()) ? "" : amtDecimal.format(cpds.getAmt());
                            table.addCell(ITextPdfUtils.singleRightCell(amtStr));
                            table.addCell(ITextPdfUtils.singleRightCell(cpds.getFinanceYymm()));
                        }
                    }
                }

                Cell cell = new Cell(1, 8);
                cell.setTextAlignment(TextAlignment.RIGHT);
                cell.add((IBlockElement) new Paragraph("合计:"));
                table.addCell(cell);
                table.addCell(ITextPdfUtils.singleRightCell(amtDecimal.format(totalQty)));
                table.addCell(ITextPdfUtils.singleRightCell(""));
                table.addCell(ITextPdfUtils.singleRightCell(amtDecimal.format(total)));
                table.addCell(ITextPdfUtils.singleRightCell(""));
                Cell cell1 = new Cell(1,12);
                cell1.add((IBlockElement) new Paragraph("组长：\t\t\t\t\t\t\t操作员：\t\t\t\t\t\t\t"));
                cell1.setTextAlignment(TextAlignment.RIGHT);
                table.addCell( cell1);
                document.add((IBlockElement) table);
                document.getPdfDocument().removeEventHandler(PdfDocumentEvent.START_PAGE, eventHandler);
            }
            document.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @NotNull
    private Map<String, Map<String, Map<String, List<CutProdDetailSalary>>>> getStringMapMap(PcCuttingSalaryReq req) {
        List<CutProdDetailSalary> list = salaryFileCreationMapper.getPcCuttingCollectByLotNo(req);
        Map<String, Map<String, Map<String, List<CutProdDetailSalary>>>> data = new LinkedHashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Iterator var5 = list.iterator();
        while (var5.hasNext()) {
            CutProdDetailSalary cpds = (CutProdDetailSalary) var5.next();
            if (ZStringUtils.isNull(data.get(cpds.getWorkerId()))) {
                data.put(cpds.getWorkerId(), new LinkedHashMap());
            }
            Map<String, Map<String, List<CutProdDetailSalary>>> dateMap = (Map) data.get(cpds.getWorkerId());
            String dateKey = sdf.format(cpds.getDispatchDate());
            if (ZStringUtils.isNull(dateMap.get(dateKey))) {
                dateMap.put(dateKey, new LinkedHashMap());
            }

            Map<String, List<CutProdDetailSalary>> lotNoMap = (Map) dateMap.get(dateKey);
            if (ZStringUtils.isNull(lotNoMap.get(cpds.getLotNo()))) {
                lotNoMap.put(cpds.getLotNo(), new ArrayList());
            }
            List<CutProdDetailSalary> lotList = (List) lotNoMap.get(cpds.getLotNo());
            lotList.add(cpds);
        }
        return data;
    }
}
